package com.usian.wemedia.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.model.admin.dtos.AdUserDto;
import com.usian.model.admin.pojos.AdUser;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmUserDto;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.common.AppJwtUtil;
import com.usian.wemedia.wemedia.mapper.WeMediaMapper;
import com.usian.wemedia.wemedia.service.LoginService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

@Service
public class LoginServiceImpl extends ServiceImpl<WeMediaMapper, WmUser> implements LoginService {

    @Override
    public ResponseResult login(WmUserDto wmUserDto) {

        //判断用户名和密码是否为空
        if (StringUtils.isEmpty(wmUserDto.getName()) || StringUtils.isEmpty(wmUserDto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "用户名和密码不能为空");
        }

        //根据用户名查询用户信息
        Wrapper wrapper = new QueryWrapper();
        ((QueryWrapper) wrapper).eq("name", wmUserDto.getName());
        WmUser one = getOne(wrapper);

        //判断wrapper是否为空
        if (one != null) {
            //md5加密
            String s = DigestUtils.md5DigestAsHex((wmUserDto.getPassword() + one.getSalt()).getBytes());
            //判断密码是否存在
            if(s.equals(one.getPassword())){
                HashMap<String, Object> map = new HashMap<>();
                map.put("password","");
                map.put("salt","");
                map.put("user",one);
                //生成token返回
                map.put("token", AppJwtUtil.getToken(one.getId().longValue()));
                return ResponseResult.okResult(map);
            }else{
                return ResponseResult.errorResult(500, "密码不正确");
            }
        } else{
            return ResponseResult.errorResult(500, "用户不存在");
        }
    }
}
